//
//  NetWorkingCache.m
//  FlowLayout
//
//  Created by Fuzzie Liu on 15/10/28.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "NetWorkingCache.h"

@implementation NetWorkingCache

+ (void)getUrl:(NSString *)url
      success:(void (^)(id result))success
      failure:(void(^)(NSError *error))failure
{
    // 获取请求数据存储文件名
    NSString *str = [url stringByReplacingOccurrencesOfString:@"/" withString:@""];
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = sandBox[0];
    NSString *caches = [sandBoxPath stringByAppendingPathComponent:str];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {
            //成功回调
            success(responseObject);
            
            BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:caches];
            if (result) {
                NSLog(@"成功缓存数据");
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (error) {
            id responseObject = [NSKeyedUnarchiver unarchiveObjectWithFile:caches];
            if (responseObject != nil) {
                success(responseObject);
                NSLog(@"网络请求失败, 成功从缓存读取数据");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前网络状态不给力" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
            }
        }
    }];
    
}


@end
